package by.dezhits.liltweets;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import by.dezhits.liltweets.api.TwitterAPI;
import by.dezhits.liltweets.db.DBHelper;
import by.dezhits.liltweets.fragment.DraftFragment;
import by.dezhits.liltweets.fragment.HomePageFragment;
import by.dezhits.liltweets.http.HttpRequestBuilder;
import by.dezhits.liltweets.notifications.NotificationsHelper;
import by.dezhits.liltweets.service.HttpService;

public class FragmentsActivity extends FragmentActivity implements
		ViewPager.OnPageChangeListener {

	private static final String CANNOT_SEND_EMPTY_MESSAGES = "Cannot send empty messages";

	private static final String CANNOT_SEARCH_FOR_EMPTY_TEXT = "Cannot search for empty text";

	private static final String WRONG_REQUEST = "Wrong request";

	private static final int NOT_SELECTED_FRAGMENT_NAME_SIZE = 30;

	private static final int SELECTED_FRAGMENT_NAME_SIZE = 40;

	private static final String TWEETING_FAILED = "Tweeting failed";

	private static final String TWEETING_SUCCESSFUL = "Tweeting successful";

	public static final String ACTION_ON_START_ACTIVITY = "by.dezhits.liltweets.ACTION_ON_START_ACTIVITY";

	public static final String ACTION_ON_PAUSE_ACTIVITY = "by.dezhits.liltweets.ACTION_ON_PAUSE_ACTIVITY";

	private BroadcastReceiver mBroadcastReceiver;

	private static final String[] FRAGMENT_NAMES = { "Home", "Draft" };
// v resourcbl massivi i znachenija
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fragments);
		this.initialisePaging();
	}

	@Override
	public void onStart() {
		super.onStart();
		mBroadcastReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				NotificationCompat.Builder nb;
				NotificationManager nm;
				if (action.equals(HttpService.ACTION_ON_SUCCESS_POSTTWEET)) {
					nb = new NotificationCompat.Builder(ContextHolder
							.getInstance().getContext())
							.setSmallIcon(android.R.drawable.star_on)
							.setContentText(TWEETING_SUCCESSFUL)
							.setTicker(TWEETING_SUCCESSFUL);
					nm = (NotificationManager) ContextHolder.getInstance()
							.getContext()
							.getSystemService(Context.NOTIFICATION_SERVICE);
					nm.notify(NotificationsHelper.SEND_TWEET, nb.build());
					nm.cancel(NotificationsHelper.SEND_TWEET);
				}

				else if (action.equals(HttpService.ACTION_ON_ERROR_POSTTWEET)) {
					nb = new NotificationCompat.Builder(ContextHolder
							.getInstance().getContext())
							.setSmallIcon(android.R.drawable.star_on)
							.setContentText(TWEETING_FAILED)
							.setTicker(TWEETING_FAILED);
					nm = (NotificationManager) ContextHolder.getInstance()
							.getContext()
							.getSystemService(Context.NOTIFICATION_SERVICE);
					nm.notify(NotificationsHelper.SEND_TWEET, nb.build());
					nm.cancel(NotificationsHelper.SEND_TWEET);

				}

				else if (action.equals(HttpService.ACTION_ON_ERROR_SEARCH)) {
					Toast.makeText(
							FragmentsActivity.this,
							intent.getStringExtra(HttpService.EXTRA_KEY_MESSAGE),
							Toast.LENGTH_LONG).show();
				}

				else if (action.equals(HttpService.ACTION_ON_SUCCESS_SEARCH)) {
					Intent i = new Intent(FragmentsActivity.this,
							SearchResultActivity.class);
					startActivity(i);
				}
			}
		};

		IntentFilter filter = new IntentFilter();
		filter.addAction(HttpService.ACTION_ON_ERROR_POSTTWEET);
		filter.addAction(HttpService.ACTION_ON_SUCCESS_POSTTWEET);
		filter.addAction(HttpService.ACTION_ON_SUCCESS_SEARCH);
		filter.addAction(HttpService.ACTION_ON_ERROR_SEARCH);
		registerReceiver(mBroadcastReceiver, filter);

		SharedPreferences sp = ContextHolder
				.getInstance()
				.getContext()
				.getSharedPreferences(getString(R.string.sync_details),
						Context.MODE_PRIVATE);
		Editor editor = sp.edit();
		editor.putBoolean(getString(R.string.activity_visible), true);
		editor.putInt(getString(R.string.count), 0);
		editor.commit();
		
		NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		nm.cancel(NotificationsHelper.SYNC_SERVICE);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onPause() {
		super.onPause();
		SharedPreferences sp = ContextHolder
				.getInstance()
				.getContext()
				.getSharedPreferences(getString(R.string.sync_details),
						Context.MODE_PRIVATE);
		Editor editor = sp.edit();
		editor.putBoolean(getString(R.string.activity_visible), false);
		editor.commit();
	}

	@Override
	public void onStop() {
		super.onStop();
		unregisterReceiver(mBroadcastReceiver);
	}

	private void initialisePaging() {
		FragmentStatePagerAdapter adapter = new FragmentStatePagerAdapter(
				getSupportFragmentManager()) {

			@Override
			public int getCount() {
				return 2;
			}

			@Override
			public Fragment getItem(int page) {
				if (page == 0) {
					return new HomePageFragment();
				} else if (page == 1) {
					return new DraftFragment();
				}
				return null;
			}
		};

		final ViewPager pager = (ViewPager) super.findViewById(R.id.viewpager);
		pager.setOnPageChangeListener(this);
		pager.setAdapter(adapter);
		final TextView tvRight = (TextView) findViewById(R.id.fragment_name_right);
		final TextView tvLeft = (TextView) findViewById(R.id.fragment_name_left);
		final RelativeLayout rlLeft = (RelativeLayout) findViewById(R.id.rl_left);
		final RelativeLayout rlRight = (RelativeLayout) findViewById(R.id.rl_right);
		tvRight.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				pager.setCurrentItem(1);
				rlLeft.setVisibility(View.INVISIBLE);
				rlRight.setVisibility(View.VISIBLE);
				tvRight.setTextSize(SELECTED_FRAGMENT_NAME_SIZE);
				tvLeft.setTextSize(NOT_SELECTED_FRAGMENT_NAME_SIZE);
			}
		});
		tvLeft.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				pager.setCurrentItem(0);
				rlLeft.setVisibility(View.VISIBLE);
				rlRight.setVisibility(View.INVISIBLE);
				tvRight.setTextSize(NOT_SELECTED_FRAGMENT_NAME_SIZE);
				tvLeft.setTextSize(SELECTED_FRAGMENT_NAME_SIZE);
			}
		});
		tvLeft.setText(FRAGMENT_NAMES[0]);
		tvRight.setText(FRAGMENT_NAMES[1]);
		tvRight.setTextSize(NOT_SELECTED_FRAGMENT_NAME_SIZE);
		tvLeft.setTextSize(SELECTED_FRAGMENT_NAME_SIZE);
		rlLeft.setVisibility(View.VISIBLE);
		rlRight.setVisibility(View.INVISIBLE);

	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int page) {
		TextView tvRight = (TextView) findViewById(R.id.fragment_name_right);
		TextView tvLeft = (TextView) findViewById(R.id.fragment_name_left);
		RelativeLayout rlLeft = (RelativeLayout) findViewById(R.id.rl_left);
		RelativeLayout rlRight = (RelativeLayout) findViewById(R.id.rl_right);
		if (page == 0) {
			tvRight.setTextSize(NOT_SELECTED_FRAGMENT_NAME_SIZE);
			tvLeft.setTextSize(SELECTED_FRAGMENT_NAME_SIZE);
			rlLeft.setVisibility(View.VISIBLE);
			rlRight.setVisibility(View.INVISIBLE);
		} else if (page == 1) {
			tvRight.setTextSize(SELECTED_FRAGMENT_NAME_SIZE);
			tvLeft.setTextSize(NOT_SELECTED_FRAGMENT_NAME_SIZE);
			rlLeft.setVisibility(View.INVISIBLE);
			rlRight.setVisibility(View.VISIBLE);
		}
	}

	public void clearListView(View v) {
		DBHelper dbh = new DBHelper(this, null);
		dbh.clearTweetsTable();
		//Not used
	}

	public void searchTweets(View v) {
		AlertDialog.Builder adb = new AlertDialog.Builder(this);
		View view = getLayoutInflater().inflate(
				R.layout.view_dialog_search_tweets, null);
		adb.setView(view);
		ImageButton searchTweets = (ImageButton) view
				.findViewById(R.id.btn_dialog_search_tweets);
		final AlertDialog ad = adb.create();
		final EditText et = (EditText) view
				.findViewById(R.id.et_dialog_search_tweets);
		searchTweets.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				NotificationCompat.Builder nb;
				NotificationManager nm;
				String s;
				if (!TextUtils.isEmpty((s = et.getText().toString()))) {
					try {
						String search = URLEncoder.encode(s, getString(R.string.utf));
						Intent intent = new Intent(FragmentsActivity.this,
								HttpService.class);
						HttpRequestBuilder httpRequestBuilder = new HttpRequestBuilder();
						httpRequestBuilder.setType(HttpRequestBuilder.Type.GET);
						httpRequestBuilder
								.setTwitterRequest(HttpRequestBuilder.TwitterRequest.SEARCH_TWEETS);
						httpRequestBuilder
								.setUrl(TwitterAPI.URL.TWITTER_SEARCH_TWEETS_URL);
						httpRequestBuilder.appendQueryParameter(
								TwitterAPI.QueryParametr.Q, search);
						intent.putExtra(HttpService.HTTP_REQUEST_BUILDER,
								httpRequestBuilder);
						startService(intent);
					} catch (UnsupportedEncodingException e) {
						Toast.makeText(FragmentsActivity.this,
								WRONG_REQUEST, Toast.LENGTH_LONG)
								.show();
					}

					nb = new NotificationCompat.Builder(ContextHolder
							.getInstance().getContext())
							.setSmallIcon(android.R.drawable.star_on)
							.setContentText(getString(R.string.searching_in_process))
							.setTicker(getString(R.string.searching_in_process));
					nm = (NotificationManager) ContextHolder.getInstance()
							.getContext()
							.getSystemService(Context.NOTIFICATION_SERVICE);
					nm.notify(NotificationsHelper.SEND_TWEET, nb.build());
					nm.cancel(NotificationsHelper.SEND_TWEET);
					ad.dismiss();
				} else {
					Toast.makeText(FragmentsActivity.this,
							CANNOT_SEARCH_FOR_EMPTY_TEXT, Toast.LENGTH_LONG)
							.show();
				}
			}
		});
		ad.show();

	}

	public void postTweet(View v) {
		AlertDialog.Builder adb = new AlertDialog.Builder(this);
		View view = getLayoutInflater().inflate(
				R.layout.view_dialog_post_tweet, null);
		adb.setView(view);
		ImageButton postTweet = (ImageButton) view
				.findViewById(R.id.btn_dialog_post_tweet);
		final AlertDialog ad = adb.create();
		final EditText et = (EditText) view
				.findViewById(R.id.et_dialog_post_tweet);
		postTweet.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				NotificationCompat.Builder nb;
				NotificationManager nm;
				String status;
				if (!TextUtils.isEmpty((status = et.getText().toString()))) {
					Intent intent = new Intent(FragmentsActivity.this,
							HttpService.class);
					HttpRequestBuilder httpRequestBuilder = new HttpRequestBuilder();
					httpRequestBuilder.setType(HttpRequestBuilder.Type.POST);
					httpRequestBuilder
							.setTwitterRequest(HttpRequestBuilder.TwitterRequest.STATUSES_UPDATE);
					httpRequestBuilder
							.setUrl(TwitterAPI.URL.TWITTER_STATUSES_UPDATE_URL);
					httpRequestBuilder.appendQueryParameter(
							TwitterAPI.QueryParametr.STATUS, status);
					intent.putExtra(HttpService.HTTP_REQUEST_BUILDER,
							httpRequestBuilder);
					startService(intent);
					nb = new NotificationCompat.Builder(ContextHolder
							.getInstance().getContext())
							.setSmallIcon(android.R.drawable.star_on)
							.setContentText(getString(R.string.tweeting_in_process))
							.setTicker(getString(R.string.tweeting_in_process));
					nm = (NotificationManager) ContextHolder.getInstance()
							.getContext()
							.getSystemService(Context.NOTIFICATION_SERVICE);
					nm.notify(NotificationsHelper.SEND_TWEET, nb.build());
					nm.cancel(NotificationsHelper.SEND_TWEET);
					ad.dismiss();
				} else {
					Toast.makeText(FragmentsActivity.this,
							CANNOT_SEND_EMPTY_MESSAGES, Toast.LENGTH_LONG)
							.show();
				}
			}
		});
		ad.show();
	}

	public void logOff(View v) {
		SharedPreferences prefs = ContextHolder
				.getInstance()
				.getContext()
				.getSharedPreferences(getString(R.string.user_details),
						MODE_PRIVATE);
		Editor edit = prefs.edit();
		edit.clear();
		edit.commit();
		Intent intent = new Intent(this, LoginActivity.class);
		startActivity(intent);
		finish();
	}

}